'use strict'

const path = require('path')
const gulp = require('gulp');
const merge = require('merge');
const jsdoc = require('jwork-jsdoc');
const { stage, cos } = require('jwork-util');
const $ = require('gulp-load-plugins')();
const packageConfig = require('./package');
const ABSOLUTE_PATH = path.resolve(process.cwd());
const NODE_ENV = process.env.NODE_ENV;
const isServer = (NODE_ENV === 'server');
const isProduction = (NODE_ENV === 'production');

//Build system config file.
const config = merge(true, {
  //Entry dir.
  entry: path.resolve(ABSOLUTE_PATH, 'src'),

  //Dist dir
  output: path.resolve(ABSOLUTE_PATH, isServer ? '.temp' : 'dist'),
  isPx2rem: stage.isMobilePlatform(packageConfig.platform) ? true : false,
  rootValue: '100px',
  isAPI: false,
  port: 10000,
  extName: '.php',
  isSass: false,
  domain: {
    cdn: ''
  }
}, (packageConfig.jwork || {}));

$.error = function(stream) {
  stream.on('error', function(error) {
    console.log(error);
  });

  return stream;
};

//Clean output files.
const clean = (() => {
  gulp.task('clean', () => {
    return gulp.src(config.output)
      .pipe($.error($.clean()));
  });
  return ['clean'];
})();

//Copy lib and plugins dirs
const libAndPlugins = (() => {

  gulp.task('lib', clean, () => {
    return gulp.src(path.resolve(config.entry, 'lib/**/**/*.*'))
      .pipe(gulp.dest(path.resolve(config.output, 'lib')));
  });

  gulp.task('plugins', ['lib'], () => {
    return gulp.src(path.resolve(config.entry, 'plugins/**/**/*.*'))
      .pipe(gulp.dest(path.resolve(config.output, 'plugins')));
  });

  return ['plugins'];
})();

//Build moudle 
const modules = (() => {
  gulp.task('md-img', libAndPlugins, () => {
    return gulp.src(path.resolve(config.entry, 'md/*/img/md_*.*'))
      .pipe($.rename({
        dirname: 'img'
      }))
      .pipe(gulp.dest(config.output));
  });

  return ['md-img'];
})();

const sass = (() => {

  gulp.task('sass', modules, () => {
    return gulp.src([path.resolve(config.entry, './**/**/*.scss')])
      .pipe($.sass().on('error', $.sass.logError))
      .pipe(gulp.dest(config.entry));
  });

  return ['sass'];
})();

const entryTask = (() => {
  let extryTaskName = config.isSass ? 'del-sass-css' : 'include';

  gulp.task('include', config.isSass ? sass : modules, () => {
    let extName = isServer ? '.html' : config.extName;
    let task = gulp.src(path.resolve(config.entry, '*.html'))
      .pipe($.fileInclude({
        prefix: '@@',
        basepath: config.entry
      }))
      .pipe($.useref())
      .pipe($.if('*.css', $.autoprefixer({
        browsers: [
          'last 10 Chrome versions',
          'last 5 Firefox versions',
          'Safari >= 6',
          'ie > 7'
        ],
        cascade: true,
        remove: true
      })))
      .pipe($.if('*.html', $.rename({
        extname: extName
      })));

    //Is px change rem.
    if (config.isPx2rem) {
      task = task.pipe($.if('*.css', $.px2rem({
        rootValue: config.rootValue,
        replace: true,
        one: false
      })));
    }

    task = isProduction ? task.pipe($.if('*.css', $.error($.cleanCss({
        advanced: true,
        compatibility: 'ie6',
        keepSpecialComments: '*'
      }))))
      .pipe($.if('*.js', $.error($.uglify()))) : task;

    //Is domain or cdn
    task = isServer ? task : task.pipe($.error($.cdn({
      domain: '(href|src) *= *( |\"|\')*(js|css|lib|plugins|img){1}([^\"\']*)',
      cdn: `$1=$2${config.domain.cdn}\/$3$4\?v=${new Date().getTime()}`
    })));

    return task.pipe(gulp.dest(config.output));
  });

  gulp.task('del-sass-css', ['include'], () => {
    return gulp.src([
        path.resolve(config.entry, './sass/**/*.css'),
        path.resolve(config.entry, './md/**/**/*.css')
      ])
      .pipe($.clean());
  });

  gulp.task('jsdoc', [extryTaskName], () => {
    return jsdoc(config.entry);
  });

  return [config.isAPI ? 'jsdoc' : extryTaskName];
})();

//Entry task for gulp.
gulp.task('server', entryTask, () => {
  gulp.watch(
    path.resolve(config.entry, '**/**/*.*'), entryTask
  );
  return $.connect.server({
    root: [config.output, process.cwd()],
    livereload: true,
    host: cos.ip,
    port: config.port
  });
});

gulp.task('default', entryTask);
